/*
 * Copyright (c) 2021
 * User:LENOVO
 * File:二叉树的锯齿形层序遍历.java
 * Date:2021/02/18 14:20:18
 */

package org.bytedance.链表和数;

import com.alibaba.fastjson.JSONObject;

import java.util.*;

public class 二叉树的锯齿形层序遍历 {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(5);
        root.right = new TreeNode(1);
        root.left.left = new TreeNode(6);
        root.left.right = new TreeNode(2);
        root.left.right.left = new TreeNode(7);
        root.left.right.right = new TreeNode(4);

        root.right.left = new TreeNode(0);
        root.right.right = new TreeNode(8);
        二叉树的锯齿形层序遍历 instance = new 二叉树的锯齿形层序遍历();
        List<List<Integer>> lists = instance.printLevelOrder(root);
        for (List<Integer> item : lists) {
            System.out.println(JSONObject.toJSONString(item));
        }
    }


    private static class TreeNode {
        int value;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int value) {
            this.value = value;
        }
    }

    public List<List<Integer>> printLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return Collections.emptyList();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        boolean reverse = false;
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> tmpRes = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll.left != null) queue.offer(poll.left);
                if (poll.right != null) queue.offer(poll.right);
                if (reverse) {
                    tmpRes.add(0, poll.value);
                } else {
                    tmpRes.add(poll.value);
                }
            }
            reverse = !reverse;
            res.add(tmpRes);
        }
        return res;
    }
}
